package com.homwee.factory;


import com.homwee.factory.util.Contants;
import com.mediatek.twoworlds.factory.MtkTvFApiDisplayTest;
import com.mediatek.twoworlds.factory.MtkTvFApiInformation;
import com.mediatek.twoworlds.tv.MtkTvUtil;
import com.mediatek.twoworlds.tv.MtkTvInputSource;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.view.Gravity;
import android.util.TypedValue;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import com.mediatek.twoworlds.tv.MtkTvInputSource;
import com.mediatek.twoworlds.tv.common.MtkTvConfigType;
import com.mediatek.twoworlds.tv.common.MtkTvConfigTypeBase;
import com.mediatek.twoworlds.tv.MtkTvBroadcast;
import com.mediatek.twoworlds.tv.MtkTvBanner;
import com.mediatek.twoworlds.tv.MtkTvBannerBase;
import android.view.View;
import android.widget.LinearLayout;
import android.os.SystemProperties;

import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;


public class FactoryStateService extends Service {
	private static final String TAG = "FactoryStateService";
        private TextView  stateText;
        private TextView  channelText;
        private TextView  keyText;
        private LinearLayout mLayout;
       	private WindowManager mWindowManager;
        private WindowManager.LayoutParams wmParams;
        private BroadcastReceiver mBroadcastReceiver = null; 
        private final String ACTION_SET_STATE = "com.homwee.stateservice.setstate";
        private final String ACTION_SET_KEY = "com.homwee.stateservice.setkey";
        private final String ACTION_SET_VISBILE = "com.homwee.stateservice.setvisble";
        private final int MESSAGE_UPDATE = 10000;
        private Handler mHandler;
        private String mBrand =SystemProperties.get("ro.product.name", "");
        private MtkTvBannerBase mBanner;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        mBanner = MtkTvBanner.getInstance();

        startForeground(0, null);
        String sourcename = MtkTvInputSource.getInstance().getCurrentInputSourceName();
        //initLayout();
        presetState(sourcename, android.graphics.Color.GREEN);
        //presetChannelValue("0",android.graphics.Color.GREEN);
        presetKeyValue("KEY", 0);
        if (mBrand.equalsIgnoreCase("ISDB92PC") ||
                mBrand.equalsIgnoreCase("ISDB95PC")) {
            presetChannelValue(" ",android.graphics.Color.BLUE);
        }
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MESSAGE_UPDATE:
                        updateInfo();
                        mHandler.removeMessages(MESSAGE_UPDATE);
                        msg = mHandler.obtainMessage();
                        msg.what = MESSAGE_UPDATE;
                        mHandler.sendMessageDelayed(msg, 3000);
                        break;
                }
            }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_SET_STATE);
        filter.addAction(ACTION_SET_KEY);
        filter.addAction(ACTION_SET_VISBILE);
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d(TAG, "get in state receiver");
                final String action = intent.getAction();
                final String text = intent.getStringExtra("text");
                final int color = intent.getIntExtra("color", android.graphics.Color.RED);
                if (ACTION_SET_STATE.equals(action)) {
                    if (mBrand.equalsIgnoreCase("ISDB92PC") ||
                            mBrand.equalsIgnoreCase("ISDB95PC")) {
                        newSanFactoryMode();
                    } else {
                        stateText.setText(text);
                        stateText.setTextColor(color);
                    }
                } else if (ACTION_SET_KEY.equals(action)) {
                    if (mBrand.equalsIgnoreCase("ISDB92PC") ||
                            mBrand.equalsIgnoreCase("ISDB95PC")) {
                        newSanFactoryMode();
                    } else {
                        keyText.setText(text);
                        keyText.setTextColor(color);
                    }
                } else if (ACTION_SET_VISBILE.equals(action)) {
                    Log.d(TAG, "visible text " + text);
                    if (text != null && text.equals("visible:true")) {
                        setVisible(true);
                    } else if (text != null && text.equals("visible:false")) {
                        setVisible(false);
                    }
                }
            }
        };
        registerReceiver(mBroadcastReceiver, filter);
        Message msg = mHandler.obtainMessage();
        msg.what = MESSAGE_UPDATE;
        mHandler.sendMessageDelayed(msg, 3000);

        //showBarCodePop();//show barcode
        return Service.START_NOT_STICKY;//START_STICKY;
    }
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.d(TAG, "cz cyf test BarCodeService onDestroy");
		android.os.Process.killProcess(android.os.Process.myPid());
                mHandler.removeMessages(MESSAGE_UPDATE);
                mWindowManager.removeView(stateText);
                mWindowManager.removeView(keyText);
                if (mBrand.equalsIgnoreCase("ISDB92PC") ||
                     mBrand.equalsIgnoreCase("ISDB95PC")) {
                    mWindowManager.removeView(channelText);
                }
                //mWindowManager.removeView(mLayout);
		unregisterReceiver(mBroadcastReceiver);
		super.onDestroy();
	}

        public void presetState(String state, int color){
            if(stateText == null){
		    stateText = new TextView(getApplicationContext());
		    wmParams = new WindowManager.LayoutParams();
		    //获取的是WindowManagerImpl.CompatModeWrapper
		    mWindowManager = (WindowManager)getApplication().getSystemService(getApplication().WINDOW_SERVICE);
		    Log.i(TAG, "mWindowManager--->" + mWindowManager);
		    //设置window type
		    wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; 
		    //设置图片格式，效果为背景透明
//		    wmParams.format = WindowManager.PixelFormat.RGBA_8888; 
		    //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
		    wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;      
		    //调整悬浮窗显示的停靠位置为左侧置顶
		    wmParams.gravity = Gravity.RIGHT | Gravity.TOP;       
		    // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
		    wmParams.x = 0;
		    wmParams.y = 60;

		    //设置悬浮窗口长宽数据  
		    wmParams.width = 200;//WindowManager.LayoutParams.WRAP_CONTENT;
		    wmParams.height = 60;//WindowManager.LayoutParams.WRAP_CONTENT;
            }
            
	    stateText.setText(state);
	    stateText.setTextSize(60);
            stateText.setAutoSizeTextTypeWithDefaults(TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM);
//            stateText.setAutoSizeTextTypeUniformWithConfiguration(20,60,1,TypedValue.COMPLEX_UNIT_SP);
	    stateText.setBackgroundColor(Color.parseColor("#13C2C2"));//android.graphics.Color.BLUE);
	    stateText.setTextColor(color);
	    stateText.setPadding(10, 10, 10, 10);// left,top,right,bottom
	    stateText.setGravity(Gravity.CENTER);
            stateText.setSingleLine(true);
            mWindowManager.addView(stateText, wmParams);
        }
        
        public void presetChannelValue(String key, int color){
            if(channelText == null){
		    channelText = new TextView(getApplicationContext());
		    wmParams = new WindowManager.LayoutParams();
		    //获取的是WindowManagerImpl.CompatModeWrapper
		    mWindowManager = (WindowManager)getApplication().getSystemService(getApplication().WINDOW_SERVICE);
		    Log.i(TAG, "mWindowManager--->" + mWindowManager);
		    //设置window type
		    wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
		    //设置图片格式，效果为背景透明
//		    wmParams.format = WindowManager.PixelFormat.RGBA_8888;
		    //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
		    wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
		    //调整悬浮窗显示的停靠位置为左侧置顶
		    wmParams.gravity = Gravity.RIGHT | Gravity.TOP;
		    // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
		    wmParams.x = 0;
		    wmParams.y = 180;

		    //设置悬浮窗口长宽数据
		    wmParams.width = 200;//WindowManager.LayoutParams.WRAP_CONTENT;
		    wmParams.height = 60;//WindowManager.LayoutParams.WRAP_CONTENT;
            }
	    channelText.setText(key);
	    channelText.setTextSize(60);
	    channelText.setBackgroundColor(Color.parseColor("#1890FF"));//android.graphics.Color.GRAY);
            channelText.setAutoSizeTextTypeWithDefaults(TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM);
	    channelText.setTextColor(android.graphics.Color.WHITE);
	    channelText.setPadding(10, 10, 10, 10);// left,top,right,bottom
	    channelText.setGravity(Gravity.CENTER);
            channelText.setSingleLine(true);
            //mLayout.addView(channelText,wmParams);
            mWindowManager.addView(channelText, wmParams);
        }
	
        
        public void presetKeyValue(String key, int color){
            if(keyText == null){
		    keyText = new TextView(getApplicationContext());
		    wmParams = new WindowManager.LayoutParams();
		    //获取的是WindowManagerImpl.CompatModeWrapper
		    mWindowManager = (WindowManager)getApplication().getSystemService(getApplication().WINDOW_SERVICE);
		    Log.i(TAG, "mWindowManager--->" + mWindowManager);
		    //设置window type
		    wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; 
		    //设置图片格式，效果为背景透明
//		    wmParams.format = WindowManager.PixelFormat.RGBA_8888; 
		    //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
		    wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;      
		    //调整悬浮窗显示的停靠位置为左侧置顶
		    wmParams.gravity = Gravity.RIGHT | Gravity.TOP;       
		    // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
		    wmParams.x = 0;
		    wmParams.y = 120;

		    //设置悬浮窗口长宽数据  
		    wmParams.width = 200;//WindowManager.LayoutParams.WRAP_CONTENT;
		    wmParams.height = 60;//WindowManager.LayoutParams.WRAP_CONTENT;
            }
	    keyText.setText(key);
	    keyText.setTextSize(60);
	    keyText.setBackgroundColor(Color.parseColor("#bfbfbf"));//android.graphics.Color.GRAY);
            keyText.setAutoSizeTextTypeWithDefaults(TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM);
	    keyText.setTextColor(android.graphics.Color.RED);
	    keyText.setPadding(10, 10, 10, 10);// left,top,right,bottom
	    keyText.setGravity(Gravity.CENTER);
            keyText.setSingleLine(true);
            mWindowManager.addView(keyText, wmParams);
            //mLayout.addView(keyText);
        }

        public void initLayout(){
            if(mLayout == null){
		    mLayout = new LinearLayout(getApplicationContext());
		    wmParams = new WindowManager.LayoutParams();
		    //获取的是WindowManagerImpl.CompatModeWrapper
		    mWindowManager = (WindowManager)getApplication().getSystemService(getApplication().WINDOW_SERVICE);
		    Log.i(TAG, "mWindowManager--->" + mWindowManager);
		    //设置window type
		    wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; 
		    //设置图片格式，效果为背景透明
//		    wmParams.format = WindowManager.PixelFormat.RGBA_8888; 
		    //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
		    wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;      
		    //调整悬浮窗显示的停靠位置为左侧置顶
		    wmParams.gravity = Gravity.RIGHT | Gravity.TOP;       
		    // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
		    wmParams.x = 0;
		    wmParams.y = 60;

		    //设置悬浮窗口长宽数据  
		    wmParams.width = 200;//WindowManager.LayoutParams.WRAP_CONTENT;
		    wmParams.height = 120;//WindowManager.LayoutParams.WRAP_CONTENT;
            }
            mLayout.setOrientation(LinearLayout.VERTICAL);
            mWindowManager.addView(mLayout, wmParams);
        }
     
       private void updateInfo(){
           String sourceName = MtkTvInputSource.getInstance().getCurrentInputSourceName();
		   if(sourceName.contains("TV")) {
               sourceName = sourceName + " " + mBanner.getChannelNumber();
           }
           int color = MtkTvBroadcast.getInstance().isSignalLoss() ? Color.RED : Color.GREEN;
           getAgingModel();

           if(mBrand.equalsIgnoreCase("ISDB92PC")||
                   mBrand.equalsIgnoreCase("ISDB95PC")){
               newSanFactoryMode();
           }else{
               stateText.setText(sourceName);
               stateText.setTextColor(color);
           }
           //if(sourceName.equals("TV") && color == Color.GREEN){
               //channelText.setText(MtkTvBanner.getInstance().getChannelNumber());
          // } else {
          //     channelText.setText("");
          // }
           
       }
       
       private void setVisible(boolean visible){
           mHandler.removeMessages(MESSAGE_UPDATE);
           if(visible == true){
               stateText.setVisibility(View.VISIBLE);
               keyText.setVisibility(View.VISIBLE);
               if (mBrand.equalsIgnoreCase("ISDB92PC") ||
                       mBrand.equalsIgnoreCase("ISDB95PC")) {
                   channelText.setVisibility(View.VISIBLE);
               }
	       Message msg = mHandler.obtainMessage();
	       msg.what = MESSAGE_UPDATE;
	       mHandler.sendMessageDelayed(msg, 3000);
           } else {
               stateText.setVisibility(View.GONE);
               keyText.setVisibility(View.GONE);
               if (mBrand.equalsIgnoreCase("ISDB92PC") ||
                       mBrand.equalsIgnoreCase("ISDB95PC")) {
                   channelText.setVisibility(View.GONE);
               }

           }
       }

       private void newSanFactoryMode(){
	        //get logo name
           String logoName="";
           logoName=MtkTvFApiInformation.getInstance().getIniParameter(
                   Contants.FACTORY_BOOTLOGOCFG_FILE, "LOGO_CFG:LOGO_NAME");
           logoName=logoName.substring(0,logoName.indexOf("."));
           Log.d("CHFactory",Contants.FACTORY_BOOTLOGOCFG_FILE+"==>"+logoName);
           keyText.setText(logoName);
           keyText.setTextColor(Color.WHITE);
           //get resolution of source
           String inputRslt=" ";
           inputRslt=mBanner.getIptsRslt();
           stateText.setText(inputRslt);
           stateText.setTextColor(Color.GREEN);
           //get channel number
           channelText.setText(mBanner.getChannelNumber());
           channelText.setTextColor(Color.WHITE);
       }

    private int getAgingModel() {
        // TODO Auto-generated method stub
        int mode = 0;
        mode = MtkTvFApiInformation
                .getInstance()
                .getIniParameter(Contants.KEYSTATUS_INI_FILEPATH,
                        Contants.FACTORY_AGE_MODE).equalsIgnoreCase("1") ? 1
                : 0;
        Log.v("tv", "in getAgingModel()=="+mode);
        if(mode==1){
            int backlightInt=1;
            int dreamTimeInt=1;
            int twoHourInt=7200000;
            try{
                backlightInt = Settings.Global.getInt(getApplicationContext().getContentResolver(), "picture_backlight");
                //pictureModeInt=Settings.Global.getInt(mContext.getContentResolver(), "picture_mode");
                dreamTimeInt=Settings.System.getInt(getApplicationContext().getContentResolver(), SCREEN_OFF_TIMEOUT);
            }catch (Settings.SettingNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(backlightInt!=100||dreamTimeInt!=twoHourInt){
                //Settings.Global.putInt(mContext.getContentResolver(), "picture_mode", 0);
                Settings.Global.putInt(getApplicationContext().getContentResolver(), "picture_backlight", 100);
                Settings.System.putInt(getApplicationContext().getContentResolver(), SCREEN_OFF_TIMEOUT, twoHourInt);
            }
        }
        return mode;
    }


}
